package gui.action;

import gui.Activator;
import gui.IImageKeys;
import gui.editor.PrivateChatEditor;
import gui.editor.PrivateChatEditorInput;
import gui.entity.AvatarEntity;

import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.SelectionProviderAction;
import org.eclipse.ui.plugin.AbstractUIPlugin;

public class PrivateChatAction extends SelectionProviderAction {

	public final static String ID = "gui.action.PrivateChatAction";

	public PrivateChatAction(final ISelectionProvider provider) {
		super(provider, "&PrivateChatAction");
		setId(ID);
		setText("&PrivateChatAction");
		setToolTipText("Chat with the selected contact.");
		setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
				Activator.PLUGIN_ID, IImageKeys.CHAT));
	}

	public void run() {
		IStructuredSelection structuredSelection = getStructuredSelection();
		Object firstElement = structuredSelection.getFirstElement();
		openEditor(((AvatarEntity) firstElement).getAvatar().name);
	}

	public static IEditorPart openEditor(final String avatarName) {
		IWorkbench workbench = PlatformUI.getWorkbench();
		IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
		IWorkbenchPage activePage = window.getActivePage();

		PrivateChatEditorInput input = new PrivateChatEditorInput(avatarName);
		if (input != null) {
			try {
				return activePage.openEditor(input, PrivateChatEditor.ID, true);
			} catch (final PartInitException pie) {
				Shell shell = window.getShell();
				ErrorDialog.openError(shell, "Error opening private chat", pie
						.getMessage(), pie.getStatus());
				Activator.getDefault().getLog().log(pie.getStatus());
			}
		}
		return null;
	}
}